<template>
  <div class="software-upgrade-container">
    <el-card
      v-loading="loading"
      element-loading-text="upgrading,please wait a moment"
    >
      <div slot="header" class="config-header">设备软件升级</div>
      <div class="upgrade-instructions">
        <el-alert
          title="提示"
          type="warning"
          :closable="false"
          show-icon
        >
          <template slot="title">
            <div class="iconSize">{{ $t('upgradeTip1') }}</div>
            <div class="iconSize">{{ $t('upgradeTip2') }}</div>
          </template>
        </el-alert>
      </div>
      <!-- action="/cgi-bin/api/upload" -->
      <el-upload
        ref="upload"
        class="upload-demo"
        :limit="1"
        action="/cgi-bin/api/upload"
        drag
        :auto-upload="true"
        :on-change="handleChange"
        :before-remove="beforeRemove"
        :on-success="handleSuccess"
        :on-error="handleError"
        :on-exceed="handleExceed"
        accept=".tar.gz"
        :file-list="fileList"
        :before-upload="beforeUpload"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div slot="tip" class="el-upload__tip">文件名必须为app.tar.gz</div>
      </el-upload>
      <el-button type="primary" class="upgradeBtn" :disabled="isUploading" @click="doUpgrade">升级设备软件</el-button>
    </el-card>
  </div>
</template>

<script>
import { parseTime } from '@/utils/index'

export default {
  data() {
    return {
      loading: false,
      file: null,
      fileList: [],
      isUploading: false
    }
  },
  methods: {
    handleExceed() {
      this.$message.warning('最多只能上传一个文件')
    },
    handleChange(file, fileList) {
      const isTarGz = file.name === 'app.tar.gz'
      if (!isTarGz) {
        this.$message.error('文件名必须为app.tar.gz')
      }
      if (fileList.length >= 2) {
        return
      }
      this.fileList = fileList // Update fileList
      this.file = file // Ensure file is set correctly
    },
    beforeRemove(file, fileList) {
      this.file = null
      this.fileList = fileList // Update fileList
    },
    beforeUpload(file) {
      const isTarGz = file.name === 'app.tar.gz'
      if (isTarGz) {
        this.isUploading = true
      }
      return isTarGz
    },
    handleError(err, file, fileList) {
      let errorMessage = '文件上传失败'
      this.isUploading = false
      if (!navigator.onLine) {
        errorMessage = '网络连接已断开，请检查您的网络'
      } else if (err.response) {
        errorMessage = `上传失败: ${err.response.status} - ${err.response.statusText}`
      } else if (err.message) {
        errorMessage = err.message
      } else {
        errorMessage = '上传失败: 未知错误'
      }
      this.$message.error(errorMessage)
    },
    handleSuccess(response, file, fileList) {
      // if (response.code !== 0) {
      //   this.$refs.upload.clearFiles()
      //   this.file = null
      //   this.$message({
      //     message: response.errMessage || 'Error',
      //     type: 'error',
      //     duration: 5 * 1000
      //   })
      //   return
      // }
      this.isUploading = false
      this.fileList = fileList // Ensure fileList is updated on success
      this.$message.success('文件已上传，点击升级设备软件按钮即可激活')
    },
    upgradeSoftware() {
      this.loading = true
      const params = {
        fileName: 'app.tar.gz',
        currTime: parseTime(new Date())
      }
      this.$store.dispatch('device/upgradeSoftware', params).then(res => {
        this.loading = false
        this.fileList = []
        this.file = null
        this.$message.success('升级成功，设备正在重启')
      }).catch((err) => {
        this.loading = false
        this.fileList = []
        this.file = null
        console.log(err)
      })
    },
    doUpgrade() {
      if (this.fileList.length === 0) {
        this.$message.error('文件不能为空')
        return
      }

      this.$confirm('是否确认升级软件，成功后设备将自动重启, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.upgradeSoftware()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消操作'
        })
      })
    }
  }
}
</script>

  <style scoped>
  .software-upgrade-container {
    padding: 20px;
  }

  .config-header {
    font-size: 16px;
    font-weight: bold;
  }

  .upgrade-instructions {
    margin-bottom: 20px;
  }

  .upload-demo {
    margin-bottom: 20px;
  }

  .el-upload__text {
    font-size: 16px;
  }

  .el-upload__tip {
    color: #888;
  }

  .upgradeBtn {
    margin-top: 20px;
  }
  </style>
